<template>
  <div class="home_page">
    <!-- <h1 style="margin: 20px 0 0 20px">账本</h1> -->
    <mt-header fixed title="账本"></mt-header>
    <div class="account">
      <h3>时间：</h3>
      <select class="mui-btn mui-btn-block" v-model="onDate">
        <option :value="item" v-for="(item,index) in dateTime" :key="index">{{item}}</option>
      </select>
      <div class="eix">
        <div>
          <span class="ex eixs">支</span>
          <span class="ex_num">{{exSum}}￥</span>
        </div>
        <div>
          <span class="ic eixs">收</span>
          <span class="ic_num">{{icSum}}￥</span>
        </div>
      </div>
    </div>

    <div class="account_data">
      <div
        v-for="(item,index) in eiList"
        :key="index"
        class="ad_item"
        :class="{move:indexs==index}"
        @touchstart="touchStart(item,index)"
        @touchend="touchEnd(item,index)"
        @click="showSelect"
      >
        <span class="ad_p">{{item.Pitch}}</span>
        <span class="ad_t">{{item.Time.slice(8,10)}}日{{item.Time.slice(11,16)}}</span>
        <span class="ad_r">{{item.Reamrk}}</span>
        <span class="ad_n" :class="index>exLength?'adn_greed':'adn_red'">{{item.Num}}￥</span>
        <div class="del" @click="deleteItem(item,index)">删除</div>
      </div>
    </div>
    <div class="bom"></div>
  </div>
</template>

<script>
import { MessageBox } from "mint-ui";
import { Toast } from "mint-ui";
export default {
  name: "homepage",
  data() {
    return {
      expend: [],
      income: [],
      onDate: "", //默认选中日期
      dateTime: [], //可选日期
      eiList: [], //现在显示的列表
      indexs: null,
      clientNum: {}, // 记录开始滑动（x1）,结束滑动（x2）的鼠标指针的位置
      candelete: {}, // 滑动的item
      vals: "",
      exLength: null, //支出的条数
      exSum: null,
      icSum: null,
    };
  },
  methods: {
    showSelect(index) {
      this.indexs = null;
    },
    deleteItem(index) {
      this.list.splice(index, 1);
      // splice方法是删除数组某条数据，或者向某个位置添加数据
    },
    touchStart(item, index) {
      this.indexs = index;
      // if(this.indexs == index) this.indexs = null
      let touchs = event.changedTouches[0];
      // 记录开始滑动的鼠标位置
      this.clientNum.x1 = touchs.pageX;
      this.candelete = {};
    },
    touchEnd(item, index) {
      this.indexs = index;
      // if(this.indexs == index) this.indexs = null
      let touchs = event.changedTouches[0];
      // 记录结束滑动的鼠标位置
      this.clientNum.x2 = touchs.pageX;
      this.candelete = {};
      // 判断滑动距离大于50，判定为滑动成功，否则失败
      if (
        this.clientNum.x2 < this.clientNum.x1 &&
        Math.abs(this.clientNum.x1) - Math.abs(this.clientNum.x2) > 50
      ) {
        event.preventDefault();
        this.candelete = item;
      } else if (
        this.clientNum.x2 > this.clientNum.x1 &&
        Math.abs(this.clientNum.x2) - Math.abs(this.clientNum.x1) > 10
      ) {
        event.preventDefault();
        this.candelete = {};
      }
    },
    //点击删除按钮
    deleteItem(item, index) {
      MessageBox.confirm(`是否要删除'${item.Pitch}'？`, "提示")
        .then(() => {
          let tos = Toast("删除成功！");
          setTimeout(() => {
            tos.close();
          }, 700);
          //从视图上删除
          this.eiList.splice(index, 1);
          //如果有+，就是收入
          if (item.Num.indexOf("+") != -1) {
            for (let i = 0; i < this.income.length; i++) {
              if (
                this.income[i].Pitch == item.Pitch &&
                this.income[i].Time == item.Time
              ) {
                this.income.splice(i, 1);
                this.income.forEach((item, index) => {
                  this.income[index].Num = parseFloat(item.Num.slice(1));
                });
                window.localStorage.setItem(
                  "incomeF",
                  JSON.stringify(this.income)
                );
                break;
              }
            }
          } else if (item.Num.indexOf("-") != -1) {
            for (let i = 0; i < this.expend.length; i++) {
              if (
                this.expend[i].Pitch == item.Pitch &&
                this.expend[i].Time == item.Time
              ) {
                this.expend.splice(i, 1);
                this.expend.forEach((item, index) => {
                  this.expend[index].Num = parseFloat(item.Num.slice(1));
                });
                window.localStorage.setItem(
                  "expendF",
                  JSON.stringify(this.expend)
                );
                break;
              }
            }
          }
        })
        .catch(() => {
          let tos = Toast("取消删除。");
          setTimeout(() => {
            tos.close();
          }, 500);
        });
    },
  },
  //更新页面，超级笨的方法
  activated() {
    let ex = [];
    let ic = [];
    this.expend = JSON.parse(window.localStorage.getItem("expendF"));
    this.income = JSON.parse(window.localStorage.getItem("incomeF"));
    //解决没有数据时账本bug问题
    if (!this.vals) {
      let arr = [];
      if (this.expend) {
        this.expend.forEach((item) => {
          arr.push(item.Time.slice(0, 7));
        });
      }
      if (this.income) {
        this.income.forEach((item) => {
          arr.push(item.Time.slice(0, 7));
        });
      }
      this.onDate = arr.sort().pop();
      this.dateTime = [this.onDate]
      this.vals = arr.sort().pop();
    } else {
      var val = this.vals;
    }
    if (this.expend) {
      ex = this.expend.filter((item) => {
        //记录总支出
        if (typeof item.Num == "number") item.Num = `-${item.Num}`;
        return item.Time.slice(0, 7) == val;
      });
    }
    if (this.income) {
      ic = this.income.filter((item) => {
        if (typeof item.Num == "number") item.Num = `+${item.Num}`;
        return item.Time.slice(0, 7) == val;
      });
    }
    this.exLength = ex.length - 1;
    this.eiList = [...ex, ...ic];
  },
  mounted() {
    this.expend = JSON.parse(window.localStorage.getItem("expendF"));
    this.income = JSON.parse(window.localStorage.getItem("incomeF"));
    let datetime = [];
    if (this.expend) {
      this.expend.forEach((item, index) => {
        datetime.push(item.Time.slice(0, 7));
      });
    }
    if (this.income) {
      this.income.forEach((item, index) => {
        datetime.push(item.Time.slice(0, 7));
      });
    }
    let datetimes = [...new Set(datetime)];
    this.dateTime = datetimes.sort();
    //默认改为最新时间
    this.onDate = this.dateTime[this.dateTime.length - 1];
  },
  watch: {
    onDate(val) {
      //感觉着方法很蠢
      let ex = [];
      let ic = [];
      if (this.expend) {
        ex = this.expend.filter((item) => {
          if (typeof item.Num == "number") item.Num = `-${item.Num}`;
          return item.Time.slice(0, 7) == val;
        });
      }
      if (this.income) {
        ic = this.income.filter((item) => {
          if (typeof item.Num == "number") item.Num = `+${item.Num}`;
          return item.Time.slice(0, 7) == val;
        });
      }
      this.exLength = ex.length - 1;
      this.exSum = ex.reduce((pre, cur) => {
        return parseFloat(cur.Num) + pre;
      }, 0);
      this.icSum = ic.reduce((pre, cur) => {
        return parseFloat(cur.Num) + pre;
      }, 0);
      this.eiList = [...ex, ...ic];
      this.vals = val;
    },
  },
};
</script>

<style scope>
.account {
  /* margin-top: 15px; */
  margin-left: 10px;
  margin-top: 40px;
}
.mui-btn {
  /* padding: 8px; */
  margin: 3px;
  border: none;
  outline: none;
}
.mui-btn-block {
  font-size: 18px;
  display: inline-block;
  width: 30%;
  /* margin-bottom: 10px; */
  padding: 15px 0;
}
.account h3 {
  display: inline;
}
.ad_item {
  display: flex;
  background-color: #fff;
  padding: 10px;
  margin: 5px 0;

  transform: translateX(0);
  transition: all 0.3s; /*滑动效果更生动*/
}
.ad_item span {
  flex: 1;
  line-height: 200%;
}
.account_data {
  background-color: #f1f2f6;
  /* padding: 10px; */
  overflow-x: hidden; /*隐藏ul x轴的滚动条*/
}
.ad_item .ad_p {
  /* border: 5px #7bed9f; */
  font-weight: bolder;
  flex: 0.6;
}
.ad_item .ad_r {
  /* flex-grow: 1.5; */
  text-align: center;
  font-size: 14px;
  line-height: 36px;
}
.ad_item .ad_n {
  flex-grow: 0.5;
  margin-left: 5px;
  text-align: end;
}
.ad_item .ad_t {
  flex-grow: 0.5;
  font-size: 12px;
  line-height: 34px;
  opacity: 0.6;
}
.bom {
  width: 100%;
  height: 54px;
}
.move {
  transform: translateX(-60px); /*滑动后x轴位移-60px,使其可见*/
}
.del {
  position: absolute;
  top: 0;
  right: -1px;
  z-index: 3;
  width: 60px;
  height: 100%;
  text-align: center;
  color: #fff;
  background-color: #ff5b45;
  transform: translateX(60px); /*默认x轴位移60px，使其隐藏*/
  line-height: 53px;
}
.ad_item .adn_red {
  color: #ff6348;
}
.ad_item .adn_greed {
  color: #1e90ff;
}
.account .ex {
  background-color: #ff6348;
}
.account .eix .eixs {
  color: #fff;
  border-radius: 10px;
  padding: 2px;
  text-align: center;
  width: 24px;
  height: 24px;
  display: inline-block;
  opacity: 0.8;
}
.account .ic {
  background-color: #1e90ff;
  margin-top: 1px;
}
.account .eix {
  margin-left: 10px;
  display: flex;
  /* width: 50%; */
}
.account .eix div {
  flex: 1;
  margin-bottom: 5px;
}
.account .eix div .ex_num,
.account .eix div .ic_num {
  margin-left: 8px;
  font-weight: bold;
  line-height: 200%;
}
</style>